<template>
  <PageContainer title="公告通知">
    <div class="notice-list-container">
      <!-- 平台筛选区域 -->
      <div class="search-section">
        <el-select
          v-model="selectedObject"
          placeholder="请选择平台"
          clearable
          @clear="loadAdminNoticeList"
          @change="loadAdminNoticeList"
          style="width: 300px"
        >
          <el-option label="全部" value="" />
          <el-option label="管理后台" value="管理后台" />
          <el-option label="作家助手" value="作家助手" />
          <el-option label="书城读者" value="书城读者" />
        </el-select>
      </div>

      <!-- 公告列表表格（其余部分不变） -->
      <div class="table-section" style="margin-top: 20px">
        <el-table
          :data="noticeList"
          :loading="loading"
          border
          stripe
          style="width: 100%"
          @row-click="handleRowClick"
          :row-class-name="(scope) => scope.row ? 'table-row-hover' : ''"
        >
          <el-table-column
            prop="title"
            label="公告标题"
            align="left"
            min-width="250"
          >
            <template #default="scope">
              <span class="title-text" :title="scope.row.title">
                {{ scope.row.title }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="tag"
            label="公告标签"
            align="center"
            width="140"
          >
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.tag)">
                {{ scope.row.tag || '无标签' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="publishTime"
            label="发布时间"
            align="center"
            width="180"
            sortable
            :sort-method="(a, b) => new Date(b.publishTime) - new Date(a.publishTime)"
          >
            <template #default="scope">
              {{ formatTime(scope.row.publishTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="creatorName"
            label="创建人"
            align="center"
            width="120"
          >
            <template #default="scope">
              {{ scope.row.creatorName || '未知' }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="220"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
                :loading="editLoading && currentNoticeId === scope.row.id"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
                :loading="deleteLoading && currentNoticeId === scope.row.id"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件（不变） -->
        <div class="pagination-section" style="margin-top: 16px">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
          />
        </div>
      </div>

      <!-- 公告详情抽屉（不变） -->
      <el-drawer
        v-model="drawerVisible"
        title="公告管理"
        direction="rtl"
        size="50%"
        :before-close="handleDrawerClose"
        :loading="detailLoading || editLoading || deleteLoading"
      >
        <div class="notice-detail" v-if="noticeDetail">
          <!-- 编辑模式 -->
          <div v-if="isEditing" class="edit-mode">
            <el-form ref="editForm" :model="editFormData" :rules="editFormRules" label-width="100px">
              <el-form-item label="公告标题" prop="title">
                <el-input
                  v-model="editFormData.title"
                  placeholder="请输入公告标题"
                  clearable
                  show-word-limit
                  maxlength="100"
                />
              </el-form-item>
              <el-form-item label="公告内容" prop="content">
                <el-input
                  type="textarea"
                  v-model="editFormData.content"
                  placeholder="请输入公告内容"
                  autosize
                  show-word-limit
                  maxlength="5000"
                />
              </el-form-item>
              <el-form-item label="公告标签">
                <el-select
                  v-model="editFormData.tag"
                  placeholder="请选择标签"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in tagOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitEdit"
                  :loading="editLoading"
                >
                  保存修改
                </el-button>
                <el-button @click="cancelEdit">取消编辑</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 查看模式 -->
          <div v-else>
            <div class="detail-header">
              <h3 class="detail-title">{{ noticeDetail.title }}</h3>
              <el-tag :type="getTagType(noticeDetail.tag)">
                {{ noticeDetail.tag || '无标签' }}
              </el-tag>
            </div>

            <div class="detail-meta">
              <span class="meta-item">发布时间：{{ formatTime(noticeDetail.publishTime) }}</span>
              <span class="meta-item">创建人：{{ noticeDetail.creatorId || '未知Id' }}</span>
            </div>

            <div class="detail-content" v-html="formatContent(noticeDetail.content)"></div>

            <div class="detail-actions">
              <el-button
                type="primary"
                @click="startEdit"
                :loading="editLoading"
              >
                编辑公告
              </el-button>
              <el-button
                type="danger"
                @click="deleteNoticeConfirm"
                :loading="deleteLoading"
              >
                删除公告
              </el-button>
            </div>
          </div>
        </div>
      </el-drawer>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import dayjs from 'dayjs';
import { getNoticeInfo } from '@/api/admin';
import { getNoticeList, updateNotice, deleteNotice } from '@/api/super'
import PageContainer from '@/components/PageContainer.vue';

// 数据状态管理
const noticeList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const selectedObject = ref(''); // 新增：选中的平台（空为“全部”）
const drawerVisible = ref(false);
const noticeDetail = ref(null);
const editForm = ref(null);
const editFormData = reactive({
  title: '',
  content: '',
  tag: ''
});
const tagOptions = reactive([
  { value: '紧急公告', label: '紧急公告' },
  { value: '重要通知', label: '重要通知' },
  { value: '活动提醒', label: '活动提醒' },
  { value: '赏罚公示', label: '赏罚公示' }
]);
const currentNoticeId = ref('');
const editLoading = ref(false);
const deleteLoading = ref(false);
const detailLoading = ref(false);
const isEditing = ref(false);

// 生命周期钩子
onMounted(() => {
  loadAdminNoticeList();
});

// 核心方法：加载公告列表（新增平台筛选逻辑）
const loadAdminNoticeList = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      object: selectedObject.value, // 传递选中的平台，空则查询全部
      keyword: '' // 若需保留关键词搜索，可继续传递searchKeyword
    };
    const response = await getNoticeList(params);
    if (response.data.code === '0000') {
      noticeList.value = response.data.data.list || [];
      totalCount.value = response.data.data.pagination?.total || 0;
    } else {
      ElMessage.error(response.data.msg || '获取数据失败');
    }
  } catch (error) {
    ElMessage.error('网络异常，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 其余方法（fetchNoticeDetail、startEdit、cancelEdit等）保持不变
const fetchNoticeDetail = async (noticeId) => {
  try {
    detailLoading.value = true;
    const response = await getNoticeInfo({ id: noticeId });
    if (response.data.code === '0000') {
      noticeDetail.value = response.data.data;
      editFormData.title = noticeDetail.value.title;
      editFormData.content = noticeDetail.value.content;
      editFormData.tag = noticeDetail.value.tag;
    } else {
      ElMessage.error(response.data.msg || '获取详情失败');
    }
  } catch (error) {
    ElMessage.error('网络异常，请稍后重试');
  } finally {
    detailLoading.value = false;
  }
};

const startEdit = () => {
  isEditing.value = true;
};

const cancelEdit = () => {
  isEditing.value = false;
  editFormData.title = noticeDetail.value.title;
  editFormData.content = noticeDetail.value.content;
  editFormData.tag = noticeDetail.value.tag;
};

const submitEdit = async () => {
  try {
    await editForm.value.validate();
    editLoading.value = true;
    const params = {
      id: noticeDetail.value.id,
      title: editFormData.title,
      content: editFormData.content,
      tag: editFormData.tag
    };
    const response = await updateNotice(params);
    if (response.data.code === '0000') {
      ElMessage.success('修改成功');
      isEditing.value = false;
      fetchNoticeDetail(currentNoticeId.value);
      loadAdminNoticeList();
    } else {
      ElMessage.error(response.data.msg || '修改失败');
    }
  } catch (error) {
    if (error.name !== 'Error') {
      ElMessage.error('请完善表单信息');
    } else {
      ElMessage.error('网络异常，请稍后重试');
    }
  } finally {
    editLoading.value = false;
  }
};

const handleEdit = async (row) => {
  currentNoticeId.value = row.id;
  await fetchNoticeDetail(row.id);
  drawerVisible.value = true;
};

const handleDelete = (row) => {
  currentNoticeId.value = row.id;
  // 弹出删除确认弹窗
  ElMessageBox.confirm(
    '确定要删除该公告吗？删除后不可恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      // 用户确认后，执行删除逻辑
      deleteNoticeConfirm();
    })
    .catch(() => {
      // 用户取消删除，提示“已取消”
      ElMessage.info('已取消删除');
    });
};

const deleteNoticeConfirm = async () => {
  try {
    deleteLoading.value = true;
    const params = { id: currentNoticeId.value };
    const response = await deleteNotice(params);
    if (response.data.code === '0000') {
      ElMessage.success('删除成功');
      drawerVisible.value = false;
      loadAdminNoticeList();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    ElMessage.error('网络异常，请稍后重试');
  } finally {
    deleteLoading.value = false;
  }
};

const handleRowClick = (row) => {
  handleEdit(row);
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  loadAdminNoticeList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadAdminNoticeList();
};

const handleDrawerClose = () => {
  drawerVisible.value = false;
};

const formatTime = (timestamp) => dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
const getTagType = (tag) => {
  const tagMap = {
    '重要通知': 'success',
    '紧急公告': 'danger',
    '活动提醒': 'primary',
    '赏罚公示': 'info'
  };
  return tagMap[tag] || 'default';
};

const formatContent = (content) => content.replace(/\n/g, '<br>');

// 表单验证规则（不变）
const editFormRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 100, message: '标题不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { max: 5000, message: '内容不能超过5000个字符', trigger: 'blur' }
  ]
};
</script>

<style lang="scss" scoped>
/* 样式部分保持不变 */
.notice-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
}

.search-section {
  padding: 8px 0;
  border-bottom: 1px solid #f2f2f2;
}

.table-section {
  margin-top: 20px;
}

.pagination-section {
  margin-top: 16px;
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.notice-detail {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .detail-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .detail-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      margin: 0 20px 0 0;
    }
  }

  .detail-meta {
    display: flex;
    gap: 24px;
    color: #606266;
    font-size: 14px;
    margin-bottom: 20px;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }

  .detail-content {
    flex: 1;
    color: #303133;
    line-height: 1.8;
    font-size: 14px;
    margin-bottom: 20px;

    p {
      margin: 0 0 16px 0;
    }
  }

  .detail-actions {
    display: flex;
    gap: 16px;
    margin-top: 16px;
  }

  .edit-mode {
    padding: 20px;
    background-color: #f9fafb;
    border-radius: 8px;
  }
}

@media (max-width: 768px) {
  .search-section .el-select {
    width: 100% !important;
  }

  .el-table__fixed-right {
    right: 0 !important;
  }

  .el-drawer.rtl {
    width: 95% !important;
  }
}
</style>